package com.food.restaurantpro.fragments;

import java.util.ArrayList;

import com.NYXDigital.NiceSupportMapFragment;
import com.food.restaurantpro.R;
import com.food.restaurantpro.RestaurantApp;
import com.food.restaurantpro.adapters.PlacesAdapter;
import com.food.restaurantpro.database.tables.PlaceTable;
import com.food.restaurantpro.log.Log;
import com.food.restaurantpro.objects.Place;
import com.food.restaurantpro.utils.AlertDialogInterface;
import com.food.restaurantpro.utils.AlertDialogManager;
import com.food.restaurantpro.utils.MarkerManager;
import com.food.restaurantpro.utils.Prefs;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class PlacesFragment extends Fragment implements LocationListener {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Runtime.getRuntime().gc();
	}

	private TextView tvHeader;
	private NiceSupportMapFragment mapFragment;
	private GoogleMap map;
	private ListView mListView;
	private ArrayList<Place> mPlaceList;
	private PlacesAdapter mPlacesAdapter;

	public static View view;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if (view != null) {
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null)
				parent.removeView(view);
		}
		try {
			view = inflater.inflate(R.layout.fragment_places, container, false);
		} catch (InflateException e) {
			Log.e("PlacesFragment", "onCreateView", e);
		}
		tvHeader = (TextView) view.findViewById(R.id.tvHeader);
		if (tvHeader != null) {
			tvHeader.setText(R.string.places);
		}

		mlocListener = this;

		mPrefs = new Prefs(RestaurantApp.CURRENT_CONTEXT);
		
		mapFragment = (NiceSupportMapFragment) getActivity()
				.getSupportFragmentManager().findFragmentById(R.id.mapFragment);

		// tinh lai chieu cao cho listview
		RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.MATCH_PARENT,
				getScreenHeight()/3);
		param.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

		mListView = (ListView) view.findViewById(R.id.lvOfMap);
		mListView.setLayoutParams(param);

		
		map = mapFragment.getMap();			
		if (map != null) {
			try {
				MapsInitializer.initialize(getActivity().getApplicationContext());
			} catch (GooglePlayServicesNotAvailableException e) {
				e.printStackTrace();
			}
		}
		
		mPlaceList = PlaceTable.getAllPlaces();
		if (mPlaceList != null && mPlaceList.size() > 0) {
			mPlacesAdapter = new PlacesAdapter(getActivity(), mPlaceList, map);
			mListView.setAdapter(mPlacesAdapter);
			mListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					// TODO Auto-generated method stub
					moveToLocation(position);
				}
			});
		}
		return view;
	}

	private int getScreenHeight() {
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay()
				.getMetrics(displaymetrics);
		return displaymetrics.heightPixels;
	}

	
	//
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		scanLocation();
	}
	// ----------------GPS--------------
	private LocationListener mlocListener;
	private LocationManager locationManager;
	private boolean network_enabled = false;
	private Location mLocation;
	private Prefs mPrefs;

	/**
	 * Enable GPS and requestLocationUpdates
	 */
	private void scanLocation() {
		if (locationManager == null) {
			locationManager = (LocationManager) getActivity().getSystemService(
					getActivity().LOCATION_SERVICE);
		}
		network_enabled = locationManager
				.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		// don't start listeners if no provider is enabled
		if (!network_enabled) {
			AlertDialogManager
					.showAlertDialog(
							getActivity(),
							new AlertDialogInterface() {

								@Override
								public void onChooseYesCallback() {
									// TODO Auto-generated method stub
									getActivity().startActivity(new Intent(
											android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
								}

								@Override
								public void onChooseNoCallback() {
									// TODO Auto-generated method stub

								}
							},
							true,
							true,
							"Cannot detect GPS",
							"Google's location service seems to be disabled, do you want to enable it?",
							"Yes", "No", false);

		} else if (mlocListener != null) {
			
			Criteria criteria = new Criteria();
			criteria.setAccuracy(Criteria.ACCURACY_FINE);
			criteria.setAltitudeRequired(false);
			criteria.setBearingRequired(false);
			criteria.setCostAllowed(true);
			criteria.setPowerRequirement(Criteria.POWER_LOW);   
			String locationProvider = locationManager.getBestProvider(criteria, true);
			
			locationManager.requestLocationUpdates(
					locationProvider, 0, 0, mlocListener);
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		if (locationManager != null && mlocListener != null) {
			mLocation = location;
			locationManager.removeUpdates(mlocListener);
			drawMarkers();
			moveToLocation(0);
			mPrefs.putStringValue(String.valueOf(mLocation.getLatitude()), Prefs.KEY_MY_LAT);
			mPrefs.putStringValue(String.valueOf(mLocation.getLongitude()), Prefs.KEY_MY_LONG);
		}
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	//---------------end GPS------------------
	
	private void drawMarkers() {
		if(mPlaceList != null) {
			//nha hang chinh la nha hang dau tien trong list
			//add marker cho nha hang chinh
			if (map != null) {
				LatLng position = new LatLng(Double.parseDouble(mPlaceList.get(0).getPlaceLat()), Double.parseDouble(mPlaceList.get(0).getPlaceLong()));
				MarkerOptions marker = new MarkerOptions();
				marker.position(position);
				marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.place_home));
				map.addMarker(marker);
			}
			//add marker cho nha hang phu
			for (int i = 1; i < mPlaceList.size(); i++) {
				LatLng position = new LatLng(Double.parseDouble(mPlaceList.get(i).getPlaceLat()), Double.parseDouble(mPlaceList.get(i).getPlaceLong()));
				MarkerManager.getInstance(getActivity()).addMarker(map,
						position, String.valueOf(i + 1));
			}
		}
	}
	
	private void moveToLocation(int index) {
		if(mPlaceList != null && mPlaceList.size() > 0 && mPlaceList.size() > index) {
			moveToLocation(Double.parseDouble(mPlaceList.get(index).getPlaceLat()), Double.parseDouble(mPlaceList.get(index).getPlaceLong()));
		}
	}
	
	private void moveToLocation(double latitude, double longitude) {
    	 // Enable MyLocation Layer of Google Map
    	map.setMyLocationEnabled(true);

        //set map type
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        // Create a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);      

        // Show the current location in Google Map        
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));

        // Zoom in the Google Map
        map.animateCamera(CameraUpdateFactory.zoomTo(15));
    }
	
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		if (locationManager != null && mlocListener != null) {
			locationManager.removeUpdates(mlocListener);
		}
		if(mPlacesAdapter != null) {
			mPlacesAdapter.clearMemoryCache();
		}
		super.onDestroyView();
	}
}
